﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO.IsolatedStorage;
using System.IO;

namespace FallingSand
{
    public partial class MainPage : PhoneApplicationPage
    {
        UIElementRenderer elementRenderer;

        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        private int _size = 16;
        private int _state = 1;
        private Grid _grid;

        private Random rand = new Random(System.DateTime.Now.TimeOfDay.Milliseconds);

        private int _sand1=0;
        private int _sand2=0;
        private int _sand3=0;

        public static bool FlushMode = false;

        private Texture2D _logo;

        private void Read()
        {
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            int score;

            try
            {
                using (var isoFileStream = new IsolatedStorageFileStream("score.txt", FileMode.Open, myStore))
                {
                    using (var isoFileReader = new StreamReader(isoFileStream))
                    {
                        score = Int32.Parse(isoFileReader.ReadLine());
                    }
                }
            }
            catch
            {
                score = 0;
            }

            HighScore.Text = "HighScore:" + score;
        }

        public MainPage()
        {
            InitializeComponent();
            
            

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            Read();
            _sand1 = rand.Next(0, (int)(SharedGraphicsDeviceManager.DefaultBackBufferWidth * .5f));
            _sand2 = rand.Next(0, (int)(SharedGraphicsDeviceManager.DefaultBackBufferWidth * .5f));
            _sand3 = rand.Next(0, (int)(SharedGraphicsDeviceManager.DefaultBackBufferWidth * .5f));

       
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            _grid = new Grid((int)(SharedGraphicsDeviceManager.DefaultBackBufferWidth ),(int) (SharedGraphicsDeviceManager.DefaultBackBufferHeight),SharedGraphicsDeviceManager.Current.GraphicsDevice);

            if (null == elementRenderer)
            {
                elementRenderer = new UIElementRenderer(this, (int)SharedGraphicsDeviceManager.DefaultBackBufferWidth, (int)SharedGraphicsDeviceManager.DefaultBackBufferHeight);
            }

            _logo =   contentManager.Load<Texture2D>("sandtransport");
            _grid.ImageToDataArray(_logo);

            // Start the timer
            timer.Start();
            Read();
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            _grid.SpawnSand(new Microsoft.Xna.Framework.Rectangle((SharedGraphicsDeviceManager.DefaultBackBufferWidth / 4) / 2, 2, 2, 5), 1);

            _grid.update();
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            elementRenderer.Render();

            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin();
            _grid.DrawTextureData(spriteBatch);
            spriteBatch.Draw(elementRenderer.Texture,Vector2.Zero,Color.White);
          spriteBatch.End();
            // TODO: Add your drawing code here
        }

 
        // Simple button Click event handler to take us to the second page
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
        }

    }
}